import { useEffect } from 'react'
import { useRequest } from 'ahooks'
import { Modal, Spin } from 'antd'

import { EmailbodyPreview } from '@/components/EmailbodyPreview'
import { SPIN_DELAY } from '@/components/Loading'
import { apiGetTemplate } from './apis'
import { popupSlot } from './utils'

export const EmailbodyPreviewModal = ({
  title,
  templateId,
  htmlBody,
  destroy,
}: {
  title: string
  templateId: string
  htmlBody: string | null | undefined
  destroy: () => void
}) => {
  const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)

  const { loading, data, run } = useRequest((id: string) => apiGetTemplate(id), {
    manual: true,
    cacheTime: 1000 * 60 * 60 * 1, // 1小时过期
    staleTime: 1000 * 10, // 10 秒新鲜
    cacheKey: `MsgManage_EmailbodyPreviewModal_${templateId}`,
  })

  const isFetch = htmlBody == null
  useEffect(() => {
    if (isFetch) run(templateId)
  }, [isFetch, run, templateId])

  return (
    <Modal
      title={title}
      width={1000}
      maskClosable
      keyboard
      cancelText="关闭"
      footer={(_o, { CancelBtn }) => <CancelBtn />}
      onCancel={onHide}
      open={open}
      afterOpenChange={afterOpenChange}
    >
      <Spin spinning={loading && data === undefined} delay={SPIN_DELAY}>
        <div style={{ height: 460 }}>
          {!(loading && data === undefined) && (
            <EmailbodyPreview style={{ height: '100%' }} htmlBody={htmlBody ?? data?.htmlBody} />
          )}
        </div>
      </Spin>
    </Modal>
  )
}
